<template>
  <a-modal
      title="操作"
      :width="800"
      :visible="visible"
      :confirmLoading="confirmLoading"
      cancelText="关闭"
      @ok="handleOk"
      @cancel="close"
  >
    <a-spin :spinning="confirmLoading">
      <a-form ref="formRef" :model="model" v-bind="layout">
        <a-form-item
            name="itemValue"
            label="数据值"
            :rules="[{ required: true, message: '请输入数据值!' }]"
        >
          <a-input v-model:value="model.itemValue" placeholder="请输入数据值"/>
        </a-form-item>
        <a-form-item
            name="itemText"
            label="名称"
            :rules="[{ required: true, message: '请输入名称!' }]"
        >
          <a-input v-model:value="model.itemText" placeholder="请输入名称"/>
        </a-form-item>
        <a-form-item
            label="排序值">
          <a-input-number v-model:value="model.sortIndex" :min="1"/>
          值越小越靠前
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script lang="ts" setup>
import { saveDictItem } from '@/api/dict'
import { reactive, Ref, ref } from 'vue'
import { FormInstance, message } from 'ant-design-vue'

const formRef = ref<FormInstance>() as Ref<FormInstance>
const visible = ref(false)
const confirmLoading = ref(false)
const model = reactive({
  dictId: '',
  itemText: '',
  itemValue: '',
  sortIndex: 1
})
const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 }
}

const add = (dictId: string) => {
  edit({
    sortIndex: 1,
    dictId
  })
}
const edit = (record: any) => {
  Object.assign(model, record)
  visible.value = true
}

defineExpose({
  add,
  edit
})

const handleOk = async () => {
  await formRef.value.validate()
  await saveDictItem(model)
  message.success('操作成功')
  visible.value = false
  emits('ok')
}
const emits = defineEmits(['ok', 'close'])

const close = () => {
  emits('close')
  visible.value = false
  formRef.value.resetFields()
}
</script>
